<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="login-box"
      size="mini"
      v-if="basic"
    >
      <h4 class="login-title">登录</h4>
      <el-form-item label="账号" prop="username">
        <el-input
          type="text"
          placeholder="请输入账号"
          v-model="form.username"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          placeholder="请输入密码"
          v-model="form.password"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          @click="toRegister"
          style="width: 57.5%; margin-left: -20%"
          >跳转注册</el-button
        >
        <el-button
          size="small"
          type="primary"
          @click="onSubmit('loginForm')"
          style="width: 57.5%; margin-left: 5%"
          >登录</el-button
        >
      </el-form-item>
      <div class="link">
        <el-link
          type="info"
          style="font-size: 10px; margin-right: 10px"
          @click="changePassword('loginForm')"
          >修改密码</el-link
        >
        <el-link
          type="info"
          style="font-size: 10px"
          @click="changeUserinfo('loginForm')"
          >修改信息</el-link
        >
      </div>
    </el-form>
    <el-form
      ref="changePass"
      :model="passwordForm"
      :rules="rulestwo"
      label-width="80px"
      class="login-box"
      size="mini"
      v-if="changepassword"
    >
      <h4 class="login-title">修改密码</h4>
      <el-form-item label="账号" prop="username">
        <el-input
          type="text"
          placeholder="请输入账号"
          v-model="passwordForm.username"
        />
      </el-form-item>
      <el-form-item label="旧密码" prop="oldpassword">
        <el-input
          type="password"
          placeholder="请输入旧密码"
          v-model="passwordForm.oldpassword"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newpassword">
        <el-input
          type="password"
          placeholder="请输入新密码"
          v-model="passwordForm.newpassword"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          @click="
            changepassword = false;
            basic = true;
          "
          style="width: 57.5%; margin-left: -20%"
          >取消</el-button
        >
        <el-button
          size="small"
          type="primary"
          @click="onSubmit2('changePass')"
          style="width: 57.5%; margin-left: 5%"
          >确定</el-button
        >
      </el-form-item>
    </el-form>
    <el-form
      ref="changeInfo"
      :model="userinfoForm"
      label-width="80px"
      class="login-box"
      size="mini"
      v-if="changeuserinfo"
    >
      <h4 class="login-title">修改信息</h4>
      <el-form-item label="姓名" prop="name">
        <el-input
          type="text"
          placeholder="请再次输入密码"
          v-model="userinfoForm.name"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          type="text"
          placeholder="请输入手机号码"
          v-model="userinfoForm.phone"
        />
      </el-form-item>
      <el-form-item label="工号" prop="usernum">
        <el-input
          type="text"
          placeholder="请输入工号"
          v-model="userinfoForm.usernum"
        />
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-select
          v-model="userinfoForm.department"
          placeholder="请选择部门"
          @change="departmentChange"
          class="theSelect"
        >
          <el-option
            v-for="item in tableDataetd"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="userinfoForm.gender"
          placeholder="请选择性别"
          @change="genderChange"
          class="theSelect"
        >
          <el-option
            v-for="item in optioner"
            :key="item.number"
            :label="item.yes"
            :value="item.yes"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="small"
          @click="
            changeuserinfo = false;
            basic = true;
          "
          style="width: 57.5%; margin-left: -20%"
          >返回</el-button
        >
        <el-button
          type="primary"
          size="small"
          @click="onSubmit3('changeInfo')"
          style="width: 57.5%; margin-left: 5%"
          >修改登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import * as userApi from "../js/userApi";
import * as api from "../js/workTimeApi";
let validateCheckPass = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入新密码"));
  } else if (value == this.passwordForm.oldpassword) {
    callback(new Error("新密码和旧密码不能一致"));
  } else {
    callback();
  }
};
export default {
  name: "Login",
  data() {
    return {
      optioner: [
        {
          number: 1,
          yes: "男",
        },
        {
          number: 0,
          yes: "女",
        },
      ],
      tableDataetd: [],
      userId: "",
      form: {
        username: "",
        password: "",
      },
      passwordForm: {
        username: "",
        oldpassword: "",
        newpassword: "",
      },
      userinfoForm: {
        name: "",
        phone: "",
        usernum: "",
        department: "",
        gender: "",
      },
      rules: {
        username: [
          { required: true, message: "账号不可为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不可为空", trigger: "blur" },
        ],
      },
      rulestwo: {
        username: [
          { required: true, message: "账号不可为空", trigger: "blur" },
        ],
        oldpassword: [
          { required: true, message: "旧密码不可为空", trigger: "blur" },
        ],
        newpassword: [
          { required: true, validator: validateCheckPass, trigger: "blur" },
        ],
      },
      basic: true,
      changepassword: false,
      changeuserinfo: false,
    };
  },
  methods: {
    toRegister() {
      this.$router.push("/register");
    },
    changeUserinfo(formName) {
      // 为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          userApi
            .login({
              username: this.form.username,
              password: this.form.password,
            })
            .then((res) => {
              if (res.status === "SUCCESS") {
                this.userId = res.data.user.id;
                this.initSession(res);
                api.getUserInfo({ userId: res.data.user.id }).then((res) => {
                  this.userinfoForm.name = res.data.name;
                  this.userinfoForm.phone = res.data.phone;
                  this.userinfoForm.usernum = res.data.userNum;
                  this.userinfoForm.department = res.data.department;
                  this.userinfoForm.gender = res.data.gender;
                });
                this.changeuserinfo = true;
                this.basic = false;
              } else {
                this.$message({
                  type: "error",
                  message: "请输入正确的账号和密码，方可修改！",
                });
              }
            });
        } else {
          return false;
        }
      });
    },
    initSession(res) {
      sessionStorage.setItem("loginFlag", "SUCCESS");
      sessionStorage.setItem("username", res.data.user.username);
      sessionStorage.setItem(
        "userInfo",
        JSON.stringify(res.data.user.userInfo)
      );
      sessionStorage.setItem("userId", JSON.stringify(res.data.user.id));
      return true;
    },
    departmentChange() {},
    genderChange() {},
    changePassword(formName) {
      this.passwordForm.newpassword = "";
      // 为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          userApi
            .login({
              username: this.form.username,
              password: this.form.password,
            })
            .then((res) => {
              if (res.status === "SUCCESS") {
                this.userId = res.data.user.id;
                this.changepassword = true;
                this.basic = false;
                this.passwordForm.username = this.form.username;
                this.passwordForm.oldpassword = this.form.password;
              } else {
                this.$message({
                  type: "error",
                  message: "请输入正确的账号和密码，方可修改！",
                });
              }
            });
        } else {
          return false;
        }
      });
    },
    onSubmit(formName) {
      // 为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          userApi
            .login({
              username: this.form.username,
              password: this.form.password,
            })
            .then((res) => {
              // console.log('login success : ',res)
              if (res.status === "SUCCESS") {
                this.$message({
                  type: "success",
                  message: res.message,
                });
                //登录成功后设置标识
                this.initSession(res);
                this.$router.push('/')
              } else {
                this.$message({
                  type: "error",
                  message: res.message,
                });
              }
            });
        } else {
          return false;
        }
      });
    },
    onSubmit2(formName) {
      // 为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          userApi
            .userUpdatePwd({
              id: this.userId,
              userName: this.passwordForm.username,
              oldPassword: this.passwordForm.oldpassword,
              newPassword: this.passwordForm.newpassword,
            })
            .then((res) => {
              // console.log('login success : ',res)
              if (res.status === "SUCCESS") {
                this.$message({
                  type: "success",
                  message: res.message,
                });
                this.form.username = this.passwordForm.username;
                this.form.password = this.passwordForm.newpassword;
                this.changepassword = false;
                this.basic = true;
              } else {
                this.$message({
                  type: "error",
                  message: res.message,
                });
              }
            });
        } else {
          return false;
        }
      });
    },
    onSubmit3(formName) {
      // 为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          userApi
            .updateUserInfo({
              pwd: this.form.password,
              userInfo: {
                id: this.userId,
                userNum: this.userinfoForm.usernum,
                name: this.userinfoForm.name,
                gender: this.userinfoForm.gender,
                department: this.userinfoForm.department,
                phone: this.userinfoForm.phone,
              },
            })
            .then((res) => {
              // console.log('login success : ',res)
              if (res.status === "SUCCESS") {
                this.$message({
                  type: "success",
                  message: res.message,
                });
                this.$router.push({
                  name: "addwork",
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.message,
                });
              }
            });
        } else {
          return false;
        }
      });
    },
  },
  created() {
    this.form.username = this.$route.params.username;
    this.form.password = this.$route.params.password;
  },
  mounted() {
    userApi.findDepartmentAll({ pageNum: 1, pageSize: 9999 }).then((res) => {
      this.tableDataetd = res.data.content;
    });
  },
};
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100vh;
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-box {
  border: 1px solid #dcdfe6;
  width: 350px;
  padding: 35px 35px 15px 15px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow: 0 0 25px #909399;
  position: relative;
}
.login-title {
  text-align: center;
  margin: 0 auto 20px auto;
  color: #303133;
}
.link {
  position: absolute;
  bottom: 7.5px;
  right: 7.5px;
}
.theSelect {
  width: 100%;
}
</style>